package com.hzdesk.media.koreabatchmatvector.logic.persenter;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.hzdesk.media.koreabatchmatvector.bean.AdvertisingBean;
import com.hzdesk.media.koreabatchmatvector.bean.AdvertisingInfo;
import com.hzdesk.media.koreabatchmatvector.bean.DeviceAttributeBean;
import com.hzdesk.media.koreabatchmatvector.bean.UserBean;
import com.hzdesk.media.koreabatchmatvector.bean.VideoFile;
import com.hzdesk.media.koreabatchmatvector.config.RBConfig;
import com.hzdesk.media.koreabatchmatvector.dao.AdvertisingBeanDaoUtils;
import com.hzdesk.media.koreabatchmatvector.dao.DeviceAttributeBeanDaoUtils;
import com.hzdesk.media.koreabatchmatvector.dao.VideoFileDaoUtils;
import com.hzdesk.media.koreabatchmatvector.inter.IDownloadRequestListenter;
import com.hzdesk.media.koreabatchmatvector.inter.NetworkRequestListener;
import com.hzdesk.media.koreabatchmatvector.logic.contract.SplashContract;
import com.hzdesk.media.koreabatchmatvector.logic.model.SplashModel;
import com.hzdesk.media.koreabatchmatvector.request.NetworkRequest;
import com.hzdesk.media.koreabatchmatvector.utils.DeleteDirTest;
import com.hzdesk.media.koreabatchmatvector.utils.FileUtil;
import com.hzdesk.media.koreabatchmatvector.utils.JsonUitl;
import com.hzdesk.media.koreabatchmatvector.utils.XMLUtil;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Response;

/**
 * Created by Administrator on 2018/6/22.
 * 杭州席媒科技有限公司  Developers  刘传华  11
 * 佛祖镇楼 bug辟易
 */

public class SplashPersenter implements SplashContract.ISplashPersenter{
    private static final String TAG = SplashPersenter.class.getSimpleName();
    private SplashContract.ISplashView mISplashView ;
    private List<String> mlist = new ArrayList<>();
    private int index = 0;
    private Context tContext ;
    private SplashContract.ISplashModel mSplashModel ;
    private final int  DOWN_START = 1;
    private final int DOWN_END = 2;
    private List<String> path ;
    private static final String ASSET_LIST_FILENAME = "assets.lst";

    // 广告信息
    private NetworkRequestListener tNetworkRequestListener = new NetworkRequestListener(){
        @Override
        public void success(Response response) {
            processAdvertisingInfor(response);
        }
        @Override
        public void fail(String s) {

        }
    };
    //  初始化可立批设备
    private NetworkRequestListener mNetworkRequestListener = new NetworkRequestListener(){
        @Override
        public void success(Response response) {
            initDevices(response);
        }
        @Override
        public void fail(String s) {
        }
    };
    // 查询设备信息
    private NetworkRequestListener fNetworkRequestListener = new NetworkRequestListener(){
        @Override
        public void success(Response response) {
            queryInfo(response);
        }
        @Override
        public void fail(String s) {

        }
    };
    private IDownloadRequestListenter mIDownloadRequestListenter = new IDownloadRequestListenter(){

        @Override
        public void success(File response, int id) {
            if(index <= mlist.size()-1){
                conversionStorage();
                index ++;
                if(index == (mlist.size()-1) ){
                    Message msg = new Message();
                    msg.what = DOWN_END;
                    mHandler.sendMessage(msg);
                }else{
                    Message msg = new Message();
                    msg.what = DOWN_START;
                    mHandler.sendMessage(msg);
                }
            }else{
                Message msg = new Message();
                msg.what = DOWN_END;
                mHandler.sendMessage(msg);
            }
        }

        @Override
        public void fail(String s) {
            if(index <= mlist.size()-1){
                index ++;

             if(index == (mlist.size()-1) ){
                    Message msg = new Message();
                    msg.what = DOWN_END;
                    mHandler.sendMessage(msg);
                }else{
                 Message msg = new Message();
                 msg.what = DOWN_START;
                 mHandler.sendMessage(msg);
             }
            }else{
                Message msg = new Message();
                msg.what = DOWN_END;
                mHandler.sendMessage(msg);
            }
        }

        @Override
        public void Progress(float progress) {

        }
    };

    private NetworkRequest downloadFile;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case DOWN_START:  // 开始下载
                    if(index < mlist.size()){
                        String Path =  DeleteDirTest.getPath("Paperless");  //文件下载到sdCard 要存的目录  Paperless无纸化 //todo  文件路径可以修改
                        String fileName = DeleteDirTest.getDownloadFileName(mlist.get(index));
                        String url = mlist.get(index);
                        downloadFile.DownLoadFile(Path,fileName,url);
                    }else{
                        Message msg_01 = new Message();
                        msg_01.what = DOWN_END;
                        mHandler.sendMessage(msg_01);
                    }
                    // 下载信息存储到 数据库
                    break;
                case DOWN_END:   // 下载完了
                    // todo 下载完了就去 复制到AdvertInfo文件里去
                    // 清空AdvertInfo 目录下的文件
                   String SavePath =  DeleteDirTest.clear();
                    // 从数据库查看开始时间和结束时间 条件查询
                    AdvertisingBeanDaoUtils utils =  new AdvertisingBeanDaoUtils(tContext);
                    long date =  new Date().getTime();
                    List<AdvertisingBean>  beanList =   utils.query(date);
                    // 适合的广告 从 Paperless目录copy 到 AdvertInfo目录
                    if(beanList != null && beanList.size() >0){
                        for (AdvertisingBean advertisingBean : beanList) {
                           String path =  advertisingBean.getPath();
                            String fileName = DeleteDirTest.getDownloadFileName(path);
                           if(!TextUtils.isEmpty(SavePath)&& !TextUtils.isEmpty(path)){  //拷贝
                               try {
                                   FileUtil.copyFile(new File(path),SavePath+"/"+fileName);
                               } catch (Exception e) {}
                           }
                        }
                    }
                    index = 0;
                    break;
            }
        }
    };
    private List<AdvertisingInfo> mlistBean;

    public SplashPersenter(SplashContract.ISplashView tISplashView) {
        this.mISplashView = tISplashView;
        mSplashModel = new SplashModel();
    }
    @Override
    public void  initUserList(Context mContext){
        SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
        String configpath =  mSharedPreferences.getString("configpath", "");
            File file = new File(configpath);
            List<UserBean> list = XMLUtil.ReadXmlFileByUser(file);
            if(list == null){
                mISplashView.addUserList(list);
            }
    }
    @Override
    public void OnClickToMainPager(){
        mISplashView.toMainPager();
    }

    @Override
    public void NetworkRequest(Context mContext) {
        mlist.clear();
        tContext = mContext;

        //  初始化可立批设备
        NetworkRequest initDevices =  new NetworkRequest();
        initDevices.setmNetworkRequestListener(mNetworkRequestListener);
        initDevices.requestServerDate(mContext,RBConfig.INIT_DEVICES);
        // 查询设备本地使用控件大小信息
        double localsize =  getLocalUserNumber();
        NetworkRequest query =  new NetworkRequest();
        query.setmNetworkRequestListener(fNetworkRequestListener);
        query.requestServerDate(mContext,RBConfig.QUERY_DEVI8CES+localsize);
      //  Log.e(TAG, "NetworkRequest: url "+ RBConfig.QUERY_DEVI8CES+localsize);
    }



    private double getLocalUserNumber() {
        double loaclUserSize = 0.0;
        //todo  获取本地文件控件使用量
        VideoFileDaoUtils videoFileDaoUtils = new VideoFileDaoUtils(tContext);
        List<VideoFile> mlist =  videoFileDaoUtils.queryAllVideoFile();
        if(mlist != null && mlist.size() >0){
            long size = 0;
            for (VideoFile videoFile : mlist) {
                size = size+ videoFile.getSize();
            }
            // todo 单位转换
            loaclUserSize = ((double) size)/1024/1024;
        }
        return loaclUserSize;
    }

    private void initDevices(Response response) {
        try {
            String NetWorkResponse = response.body().string();
            JSONObject jsonObject = new JSONObject(NetWorkResponse);
            int Code = JsonUitl.getParsinCode(jsonObject);
            if(Code == 100){
                //  第一次 初始化成功 弹出提示框
                mISplashView.showDialog();
            }
        } catch (Exception e) {}
    }


    // 查询设备信息
    private void queryInfo(Response response) {
        DeviceAttributeBean deviceAttributeBean = (DeviceAttributeBean) JsonUitl.NetworkResponseDateDeal(response,DeviceAttributeBean.class);
        // 数据存储到数据库
        DeviceAttributeBeanDaoUtils mDeviceAttributeBeanDaoUtils = new DeviceAttributeBeanDaoUtils(tContext);
        mDeviceAttributeBeanDaoUtils.insertDeviceAttributeBean(deviceAttributeBean);
        Log.e(TAG, "queryInfo:数据存储到数据库  " );
        if(deviceAttributeBean != null){
            //  处理逻辑业务 根据type 1 广告机 2非广告机 判断是否需要加载广告
            if(deviceAttributeBean.type == 1){          // 广告机
                //  广告信息
                NetworkRequest advertising = new NetworkRequest();
                advertising.setmNetworkRequestListener(tNetworkRequestListener);
                advertising.requestServerDate(tContext, RBConfig.ADVERTISING_INFO);

            }else if(deviceAttributeBean.type == 2){    //2 非 广告机
                // 将assets 中的广告拷贝到 sdcard advertising 文件夹中但是在拷贝之前会先清空advertising目录下的文件和文件夹
                DeleteDirTest.clear();
                DeleteDirTest.copyAssetsSD(tContext);  //  数据没有正真读取过去
            }
            //  存储数据
            mSplashModel.saveDevicesDate(deviceAttributeBean,tContext);
        }
    }


    // 处理广告信息
    private void processAdvertisingInfor(Response response) {
        try {
            String NetWorkResponse = response.body().string();
            JSONObject jsonObject = new JSONObject(NetWorkResponse);
            int Code = JsonUitl.getParsinCode(jsonObject);
            if (Code == 100) {
                String normalDate = JsonUitl.getStringDateFeld(jsonObject);
                Type listType = new TypeToken<List<AdvertisingInfo>>() {}.getType();
                mlistBean = (List<AdvertisingInfo>) JsonUitl.mGson.fromJson(normalDate, listType);
                if(mlistBean != null && mlistBean.size() > 0){
                    //   往容器器添加了广告信息的url 然后批量下载广告到本地文件  /sdcard/Deskmedia/AdvertInfo/
                    boolean flage = DeleteDirTest.crteateSdCrad("Paperless");
                    // 创建绝对路径集合：
                    path = new ArrayList<>();
                    for (AdvertisingInfo advertisingInfo : mlistBean) {
                        String url =   advertisingInfo.getFileUrl();
                        //   下载信息存储到 数据库
                        if(url != null && !TextUtils.isEmpty(url)){
                            mlist.add(RBConfig.FILE_HOST_IP+url);
                            //  得到绝对路径 放到容器中
                            path.add(DeleteDirTest.getPath("Paperless")+"/"+DeleteDirTest.getDownloadFileName(url));   // 下载文件的绝对路径
                        }
                    }
                    if(flage){
                        index = 0 ;                                                                 // 下载 广告文件
                       DownLoadAdvert();
                    }                                                                               //  做 数据库存储数据
                    mSplashModel.saveAdvertisingInfo(mlistBean);
                }
            }else{                                                                                  //  code 为非 100;
                Log.e(TAG, "processAdvertisingInfor: code 为非 100 ");
            }
        }catch (Exception e){}
    }
    // 下载广告
    private void DownLoadAdvert() {
        downloadFile = new NetworkRequest();
        downloadFile.setmIDownloadRequestListenter(mIDownloadRequestListenter);
        Message msg = new Message();
        msg.what = DOWN_START;
        mHandler.sendMessage(msg);
    }
    //数据转换存储
    private void conversionStorage() {
       // Log.e(TAG, "conversionStorage: mlistBean.size()  "+mlistBean.size() );
        // 将加载到的广告信息存放到数据库
        if(mlistBean != null && mlistBean.size() > 0){
            // 将数据转换
            AdvertisingInfo bean =   mlistBean.get(index);
            AdvertisingBean advertisingBean = new  AdvertisingBean();
            advertisingBean.setAdvertId(bean.getAdvertId());
            advertisingBean.setDeviceId(bean.getDeviceId());
            advertisingBean.setEndTime(bean.getEndTime());
            advertisingBean.setFileType(bean.getFileType());
            advertisingBean.setName(bean.getName());
            advertisingBean.setStartTime(bean.getStartTime());
            advertisingBean.setStatus(bean.getStatus());
            advertisingBean.setPath(path.get(index));
            advertisingBean.setId(bean.getId());
            AdvertisingBeanDaoUtils utils =  new AdvertisingBeanDaoUtils(tContext);
            boolean flag =  utils.insertAdvertising(advertisingBean);
        }
    }
    @Override
    public void CopyFile(Context mContext) {
        copy(mContext);
    }

    private void copy(Context mContext) {
        List<String> srcFiles = new ArrayList<String>();
        String Path = getSDPath();
        if(Path != null){
            try {
                List<String> assets = getAssetsList(mContext);
                for( String asset : assets ) {
                    //如果不存在，则添加到copy列表
                    if( ! new File(Path,asset).exists() ) {
                        srcFiles.add(asset);
                    }
                }
                for( String file : srcFiles ) {
                    copyFile(file,mContext);
                }
            } catch (IOException e) {
                Log.e("CopyFileActivity", "copy: "+e);
            }
        }
    }
    public void copyFile(String asset,Context mContext){
        File destinationFile = null;
        try {
            InputStream source = mContext.getAssets().open(new File(asset).getPath());
            destinationFile = new File(getSDPath(), asset);
            destinationFile.getParentFile().mkdirs();
            OutputStream destination = new FileOutputStream(destinationFile);
            byte[] buffer = new byte[1024];
            int nread;
            while ((nread = source.read(buffer)) != -1) {
                if (nread == 0) {
                    nread = source.read();
                    if (nread < 0)
                        break;
                    destination.write(nread);
                    continue;
                }
                destination.write(buffer, 0, nread);
            }
            destination.close();
        } catch (IOException e) {
            Log.e("CopyFileActivity", "copyFile: "+e );
        }finally {
            // todo 显示文件
            //Glide.with(this).load(destinationFile.getAbsolutePath()).into(activityCopyIvBg);
        }
    }
    public String getSDPath(){
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if(sdCardExist)
        {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString()+"/Watermark";
    }
    protected List<String> getAssetsList(Context mContext) throws IOException {
        List<String> files = new ArrayList<String>();
        InputStream listFile = mContext.getAssets().open(new File(ASSET_LIST_FILENAME).getPath());
        BufferedReader br = new BufferedReader(new InputStreamReader(listFile));
        String path;
        while (null != (path = br.readLine())) {
            files.add(path);
        }
        return files;
    }
}
